package com.dragon.mmochat.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.dragon.mmochat.model.deal.MmochatBigMoneyDeal;
import com.dragon.mmochat.model.enumType.MmochatBigMoneyDealState;
import com.dragon.mmochat.model.enumType.MmochatBigMoneyDealType;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class MmochatBigMoneyDealDao extends SimpleJdbcDaoSupport {
	private static final BigMoneyDealMapper dealMapper = new BigMoneyDealMapper();

	// 读取所有未结束的交易
	private static final String getAllUnclosedDealSql = "select * from bigmoney_deal where state = 0";

	public List<MmochatBigMoneyDeal> getAllUnclosedDeal() {
		return getSimpleJdbcTemplate().query(getAllUnclosedDealSql, dealMapper);
	}

	// 创建新订单号
	private static final String createNewOrderIdSql = "select nextval('bigmoney_deal_id_seq'::regclass)";

	public int createNewOrderId() {
		return getSimpleJdbcTemplate().queryForInt(createNewOrderIdSql);
	}

	// 创建新订单
	private static final String createNewOrderSql = "insert into bigmoney_deal(id, type, price, "
			+ "amount, start_tick, roleid, rest, state) values(?, ?, ?, ?, ?, ?, ?, ?)";

	public void createNewOrder(MmochatBigMoneyDeal newOrder) throws Exception {
		getSimpleJdbcTemplate().update(createNewOrderSql, newOrder.getId(),
				newOrder.getType().getKey(), newOrder.getPrice(),
				newOrder.getAmount(), newOrder.getStartTick(),
				newOrder.getRoleId(), newOrder.getRest(),
				newOrder.getState().getKey());
		// Connection conn = null;
		// try {
		// conn = getJdbcTemplate().getDataSource().getConnection();
		// PreparedStatement ps = conn.prepareStatement(createNewOrderSql);
		// ps.setInt(1, newOrder.getType().getKey());
		// ps.setInt(2, newOrder.getPrice());
		// ps.setInt(3, newOrder.getAmount());
		// ps.setLong(4, newOrder.getStartTick());
		// ps.setInt(5, newOrder.getRoleId());
		// ps.setInt(6, newOrder.getRest());
		// ps.setInt(7, newOrder.getState().getKey());
		// ps.execute();
		// int nInserted = ps.getUpdateCount();
		// if (nInserted == 1 && ps.getMoreResults()) {
		// ResultSet rs = ps.getResultSet();
		// if (rs.next()) {
		// int id = rs.getInt(1);
		// newOrder.setId(id);
		// }
		// }
		// } catch (Exception e) {
		// throw e;
		// } finally {
		// if (conn != null) {
		// try {
		// conn.close();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		// }
	}

	// 更新订单
	private static final String updateOrderSql = "update bigmoney_deal set rest = rest - ?,"
			+ "state = ?, dealmap = ? where id = ?";

	public void updateOrder(int del, int state, String dealmap, int id) {
		getSimpleJdbcTemplate().update(updateOrderSql, del, state, dealmap, id);
	}

	// 批量更新订单状态
	private static final String batchUpdateOrderStateSql = "update bigmoney_deal set state = ? where id = ?";

	public void batchUpdateOrderState(List<Object[]> args) {
		getSimpleJdbcTemplate().batchUpdate(batchUpdateOrderStateSql, args);
	}

	// 删除2个月前的订单
	private static final String delBigMoneyDealOrderByTimeSql = "delete from bigmoney_deal "
			+ "where start_tick < ?";

	public void delBigMoneyDealOrderByTime(long time) {
		getSimpleJdbcTemplate().update(delBigMoneyDealOrderByTimeSql, time);
	}

	static class BigMoneyDealMapper implements
			ParameterizedRowMapper<MmochatBigMoneyDeal> {
		@Override
		public MmochatBigMoneyDeal mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			MmochatBigMoneyDeal deal = new MmochatBigMoneyDeal();
			deal.setId(rs.getInt("id"));
			deal.setType(MmochatBigMoneyDealType.get(rs.getInt("type")));
			deal.setState(MmochatBigMoneyDealState.get(rs.getInt("state")));
			deal.setPrice(rs.getInt("price"));
			deal.setAmount(rs.getInt("amount"));
			deal.setRest(rs.getInt("rest"));
			deal.setStartTick(rs.getLong("start_tick"));
			deal.setRoleId(rs.getInt("roleid"));

			Gson gson = new Gson();

			String str = rs.getString("dealmap");
			if (str != null) {
				Map<Integer, Integer> dealmap = gson.fromJson(str,
						new TypeToken<Map<Integer, Integer>>() {
						}.getType());
				if (dealmap != null) {
					deal.setDealerMap(dealmap);
				}
			}
			return deal;
		}
	}
}
